<template>
  <button id="btn1" @click="activeClick">激活地图事件</button>
  <button id="btn2" @click="unClick">移除地图事件</button>
</template>
<script setup>
import { inject, onMounted } from 'vue'
let $map
const source = new ol.source.Vector({}) //创建空的source
onMounted(() => {
  $map = inject('$map')
  addLayer()
})
function addLayer() {
  const style = new ol.style.Style({
    image: new ol.style.Circle({
      radius: 17,
      // 填充色,必选项
      fill: new ol.style.Fill({
        color: 'red',
      }),
      //描边,
      stroke: new ol.style.Stroke({
        width: 2, //以经纬度为标准
        color: '#333',
      }),
    }),
  })
  /* 3、创建矢量图层,添加source  source-layer */
  const layer = new ol.layer.Vector({
    source,
    style,
  })
  $map.addLayer(layer)
}
function activeClick() {
  $map.un('click', handleMap) // 解绑之前的点击事件监听器
  $map.on('click', handleMap) // 添加新的点击事件监听器
}
function unClick() {
  $map.un('click', handleMap)// 解绑当前的点击事件监听器
  source.clear() 
}

function handleMap(evt) {
  var position = evt.coordinate
  let point = new ol.Feature({
    geometry: new ol.geom.Point(position),
  })
  source.addFeature(point)
}
</script>
<style scoped>
#btn1 {
  position: fixed;
  top: 0;
  left: 0;
}
#btn2 {
  position: fixed;
  top: 0;
  left: 100px;
}
</style>
